package server;

import javax.swing.*;

import java.awt.event.*;
import java.awt.*;
import java.awt.geom.Arc2D;

public class GameTimer extends JComponent {

	private int totalTime;
	private int remainingTime;
	private int timerDiameter;
	private int timerRadius;
	private Timer ticker;

	public GameTimer() {
		ActionListener tickListener = new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent ae) {
				timerTick();
			}
		};
		ticker = new Timer(1000, tickListener);
		this.setPreferredSize(new Dimension(250, 250));
	}

	public void setTimerSize(int diameter) {
		timerDiameter = diameter;
		timerRadius = timerDiameter / 2;
	}

	public void setTime(int seconds) {
		totalTime = seconds;
		remainingTime = seconds;
	}

	private double getSlice() {

		double usedTimePortion = ((double) (totalTime - remainingTime)) / ((double) (totalTime));

		// endAngleValue = 450-(usedTimePortion*360);

		return ((-360) * usedTimePortion);
	}

	public void start() {
		ticker.start();
	}

	public void stop() {
		ticker.stop();
	}

	@Override
	public void paintComponent(Graphics g) {
		super.paintComponent(g);

		Graphics2D g2 = (Graphics2D) g;

		g.setColor(Color.red);
		g.fillOval(0, 0, timerDiameter, timerDiameter);

		g2.setColor(Color.black);
		Arc2D.Float arc = new Arc2D.Float(Arc2D.PIE);
		arc.setFrame(0, 0, timerDiameter, timerDiameter);
		arc.setAngleStart(90);
		arc.setAngleExtent(getSlice());
		g2.fill(arc);

                int c = GameShowServer.getNumContestants();
                int r = GameShowServer.getNumResponses();
		if (remainingTime > 0 && GameShowServer.getNumContestants() > GameShowServer.getNumResponses()) {
			g.setColor(Color.white);
			g.setFont(new Font("Arial", Font.PLAIN, 35));
			g.drawString(String.valueOf(remainingTime), 33, 60);
		} else {
                    Server.changeGameTab();
                }

	}
	
	public int timeRemaining(){
		return remainingTime;
	}

	public void timerTick() {
		remainingTime--;
		repaint();
		if (remainingTime <= 0) {
			stop();
		}
	}

}
